/**
 * 录入简历
 */
import React, { useState } from 'react';
import { Col, Form, Row, Tabs, Anchor, Button, Icon, message, Spin } from 'antd';
// import { history } from 'umi';
import useRequest from '@ahooksjs/use-request';
import moment from 'moment';
import isEmpty from 'lodash/isEmpty';
import { BottomAction } from '@/components';
import { PageContainer } from '@/molecules';
import { eventTrack } from '@/utils/track';
// import { sameTabProps } from '@/utils/tab';
import pageTabUtil from '@/utils/pageTabUtil';
import { getTabContainer } from '@/utils/utils';

import { base64toURL } from './utils';

import {
    ResumePreview,
    ResumeBrief,
    ResumeBase,
    ResumeWorkInfo,
    ResumeProjectInfo,
    ResumeEducation,
    ResumeCertificate,
    ResumeSkill,
    ResumeSkillLanguage,
    ResumeOther,
    ResumeTraining,
    ResumeUpload,
    ResumeRepeatModal
} from '../containers';
import {
    editStandardResumes,
    setStandardResumes,
    analysisResume,
    getResumesDetail,
    checkResumeExists,
    checkResumeDuplicate
} from '../service';
import { getFields, transformFileList } from '../utils';

const { TabPane } = Tabs;
const { Link } = Anchor;

const Record = ({ location, form }) => {
    const { query } = location;
    const { id, recruitCode } = query;
    const [submitting, setSubmitting] = React.useState(false); // 控制loading状态
    const [previewUrl, setPreviewUrl] = React.useState();
    const [repeatModalVisible, setRepeatModalVisible] = React.useState(false);
    const [repeatTalentInfo, setRepeatTalentInfo] = React.useState({});
    const [resourceRelation, setResourceRelation] = React.useState([]);
    const { loading: analysisLoading, data: analysisData, run: fetchAnalysis, mutate } = useRequest(analysisResume, {
        manual: true
    });
    const { loading: detailLoading, data: resumeDetail, run: fetchResumeDetail } = useRequest(getResumesDetail, {
        manual: true
    });

    const [keysIsReady, setKeysIsReady] = React.useState(false);
    const [detailKeysIsReady, setDetailKeysIsReady] = React.useState(false);
    const [previewChanged, setPreviewChanged] = React.useState(false);

    React.useEffect(() => {
        if (id) {
            fetchResumeDetail(id);
        }
    }, [id]);

    // 详情赋值
    React.useEffect(() => {
        if (!resumeDetail) {
            return;
        }
        const { data = {} } = resumeDetail;
        const { talentStandardDetailVO: detail, talentOriginalDetailVO: original = {} } = data;
        const { talentOriginalFileUrl: url = '' } = original;

        if (url) {
            setPreviewUrl(url);
        }

        const workInfoKeys = detail?.talentWorkDetailVOList?.map((_, index) => index) || [];
        const projectInfoKeys = detail?.talentProjectDetailVOList?.map((_, index) => index) || [];
        const educationKeys = detail?.talentEduDetailVOList?.map((_, index) => index) || [];
        const trainingKeys = detail?.talentTrainDetailVOList?.map((_, index) => index) || [];
        const certificateKeys = detail?.talentCertificateDetailVOList?.map((_, index) => index) || [];
        const skillKeys = detail?.talentSkillDetailVOList?.map((_, index) => index) || [];
        const skillLanguageKeys = detail?.talentLangDetailVOList?.map((_, index) => index) || [];

        const workInfo = getFields(detail?.talentWorkDetailVOList, 'workInfo');
        const projectInfo = getFields(detail?.talentProjectDetailVOList, 'projectInfo');
        const education = getFields(detail?.talentEduDetailVOList, 'education');
        const training = getFields(detail?.talentTrainDetailVOList, 'training');
        const certificate = getFields(detail?.talentCertificateDetailVOList, 'certificate');
        const skill = getFields(detail?.talentSkillDetailVOList, 'skill');
        const skillLanguage = getFields(detail?.talentLangDetailVOList, 'skillLanguage');

        const talentBirth = detail?.talentBirth ? moment(detail?.talentBirth) : undefined;
        const talentStartWorkTime = data?.talentStartWorkTime ? moment(data?.talentStartWorkTime) : undefined;

        const resumeAttachmentList = transformFileList(detail?.resumeAttachmentList);

        const avatar = data?.talentAvatarFile || [];
        const lastAvatar = avatar[avatar.length - 1];
        const allFileListObj = {
            uid: lastAvatar?.keyName,
            keyName: lastAvatar?.keyName,
            name: lastAvatar?.originName,
            oldName: lastAvatar?.originName,
            url: lastAvatar?.url
        };
        const allFileList = lastAvatar ? [allFileListObj] : [];

        const avatarRelation = {
            allFileList,
            uploadResourceFile: null
        };

        const finalFieldsKeys = {
            createTime: data?.createTime,
            dutyName: data?.dutyName,
            dutyCode: data?.dutyCode,
            departmentName: data?.departmentName,
            departmentCode: data?.departmentCode,
            resumeChannelCode: data?.resumeChannelCode || undefined,
            resumeChannelName: data?.resumeChannelName || undefined,
            resumeAttachmentList,

            avatarRelation,
            talentName: data?.talentName,
            phoneAreaCode: data?.phoneAreaCode,
            talentPhone: data?.talentPhone,
            talentEmail: data?.talentEmail,
            talentIdCard: detail?.talentIdCard,
            overseaEducationFlag: detail?.overseaEducationFlag,
            overseaExperienceFlag: detail?.overseaExperienceFlag,
            talentBirth,
            talentStartWorkTime,
            talentSex: data?.talentSex,
            address: data?.address ? data?.address?.split(',') : undefined,
            talentNativePlace: data?.talentNativePlace ? data?.talentNativePlace?.split(',') : undefined,
            talentWorkType: String(data?.talentWorkType || '1'),
            workInfoKeys,
            projectInfoKeys,
            educationKeys,
            trainingKeys,
            certificateKeys,
            skillKeys,
            skillLanguageKeys
        };

        const finalFieldsValue = {
            ...workInfo,
            ...projectInfo,
            ...education,
            ...training,
            ...certificate,
            ...skill,
            ...skillLanguage
        };

        if (!detailKeysIsReady) {
            setDetailKeysIsReady(true);
            form.setFieldsValue(finalFieldsKeys);
        }

        if (detailKeysIsReady) {
            form.setFieldsValue(finalFieldsValue);
        }
    }, [resumeDetail, detailKeysIsReady]);

    // 简历解析
    React.useEffect(() => {
        if (!previewUrl || !previewChanged) {
            return;
        }
        message.info('简历解析开始...');
        mutate(null);
        fetchAnalysis({ resumeFileUrl: previewUrl });
    }, [previewUrl, previewChanged]);

    // 简历解析值赋值
    React.useEffect(() => {
        if (!analysisData || !previewChanged) {
            return;
        }
        const formVal = form.getFieldsValue();
        const { data = {} } = analysisData;
        const { talentStandardDetailVO: detail, talentPhone = '' } = data;

        const workInfoKeys = detail?.talentWorkDetailVOList?.map((_, index) => index) || [];
        const projectInfoKeys = detail?.talentProjectDetailVOList?.map((_, index) => index) || [];
        const educationKeys = detail?.talentEduDetailVOList?.map((_, index) => index) || [];
        const trainingKeys = detail?.talentTrainDetailVOList?.map((_, index) => index) || [];
        const certificateKeys = detail?.talentCertificateDetailVOList?.map((_, index) => index) || [];
        const skillKeys = detail?.talentSkillDetailVOList?.map((_, index) => index) || [];
        const skillLanguageKeys = detail?.talentLangDetailVOList?.map((_, index) => index) || [];

        const workInfo = getFields(detail?.talentWorkDetailVOList, 'workInfo');
        const projectInfo = getFields(detail?.talentProjectDetailVOList, 'projectInfo');
        const education = getFields(detail?.talentEduDetailVOList, 'education');
        const training = getFields(detail?.talentTrainDetailVOList, 'training');
        const certificate = getFields(detail?.talentCertificateDetailVOList, 'certificate');
        const skill = getFields(detail?.talentSkillDetailVOList, 'skill');
        const skillLanguage = getFields(detail?.talentLangDetailVOList, 'skillLanguage');

        const talentBirth = detail?.talentBirth ? moment(detail?.talentBirth) : undefined;
        const talentStartWorkTime = data?.talentStartWorkTime ? moment(data?.talentStartWorkTime) : undefined;

        // 特殊兼容国外解析电话号码
        const isForeign = talentPhone.includes('+65');
        const finalPhoneAreaCode = isForeign ? '65' : '86';
        const finalTalentPhone = talentPhone.replace(' ', '').replace('(+65)', '');
        const finalFieldsKeys = {
            // dutyName: data?.dutyName,
            // dutyCode: data?.dutyCode,
            // departmentName: data?.departmentName,
            // departmentCode: data?.departmentCode,
            resumeChannelCode: data?.resumeChannelCode || formVal.resumeChannelCode,
            resumeChannelName: data?.resumeChannelName || formVal.resumeChannelName,

            talentName: data?.talentName || formVal.talentName,
            phoneAreaCode: finalPhoneAreaCode,
            talentPhone: finalTalentPhone || formVal.talentPhone,
            talentEmail: data?.talentEmail || formVal.talentEmail,
            address: data?.address,
            avatarRelation: data?.avatarRelation,
            talentIdCard: detail?.talentIdCard,
            overseaEducationFlag: detail?.overseaEducationFlag,
            overseaExperienceFlag: detail?.overseaExperienceFlag,
            talentBirth,
            talentStartWorkTime,
            talentSex: data?.talentSex,
            talentNativePlace: data?.talentNativePlace ? data?.talentNativePlace?.split(',') : undefined,
            talentWorkType: String(data?.talentWorkType || '1'),
            workInfoKeys,
            projectInfoKeys,
            educationKeys,
            trainingKeys,
            certificateKeys,
            skillKeys,
            skillLanguageKeys
        };

        const finalFieldsValue = {
            ...workInfo,
            ...projectInfo,
            ...education,
            ...training,
            ...certificate,
            ...skill,
            ...skillLanguage
        };
        if (!keysIsReady) {
            setKeysIsReady(true);
            form.setFieldsValue(finalFieldsKeys);
        }

        if (keysIsReady) {
            form.setFieldsValue(finalFieldsValue);
            message.success('简历解析完成');
        }
    }, [analysisData, keysIsReady, previewChanged]);

    const goBack = () => {
        pageTabUtil.goBack();
    };

    const [duplicateResumeArr, setDuplicateResumeArr] = useState([]); // 简历查重用数组
    // 提交简历
    const submitResume = async (params, arrLength = 0) => {
        try {
            setSubmitting(true);
            if (id) {
                // 编辑简历
                const res = await editStandardResumes({ ...params, id });
                if (res.code === 10000) {
                    message.success(res.msg);
                    goBack();
                } else {
                    message.error(res.msg);
                }
            } else {
                const res = await setStandardResumes(params);
                if (res.code === 10000) {
                    if (arrLength === 0) {
                        message.success(res.msg);
                    } else {
                        message.success('录入并覆盖简历成功');
                    }
                    goBack();
                } else {
                    message.error(res.msg);
                }
            }
            setSubmitting(false);
        } catch (e) {
            setSubmitting(false);
        }
    };

    /**
     * 简历查重，传姓名+手机+邮箱，talentName,talentEmail,talentPhone
     */
    const checkDuplicate = async talentObj =>
        new Promise(async resolve => {
            try {
                const { code, data = [] } = await checkResumeDuplicate(talentObj);
                if (code !== 10000) {
                    console.error('推荐时简历查重失败');
                    resolve([]);
                    return;
                }
                if (data.length === 0) {
                    // 无重复的情况
                    resolve([]);
                    return;
                }
                // 出现重复
                resolve(data);
            } catch (error) {
                resolve([]); // 接口挂了就当没查到
            }
        });

    /**
     * 处理提交按钮点击
     */
    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            console.log('处理提交按钮点击');
            console.log(values);
            try {
                if (!err) {
                    setSubmitting(true);
                    // 转换值
                    const workInfo = values?.workInfoKeys.map(k => {
                        const endTime = values?.workInfoStartTime?.[k]?.[1];
                        return {
                            startTime: values?.workInfoStartTime?.[k]?.[0]?.format('YYYY-MM-DD'),
                            endTime: endTime ? endTime.format('YYYY-MM-DD') : '',
                            industryType: values?.workInfoIndustryType[k],
                            companyName: values?.workInfoCompanyName[k],
                            departmentName: values?.workInfoDepartmentName[k],
                            positionName: values?.workInfoPositionName[k],
                            leaveReason: values?.workInfoLeaveReason[k],
                            workDesc: values?.workInfoWorkDesc[k],
                            companyNature: values?.workInfoCompanyNature[k]
                        };
                    });

                    const projectInfo = values?.projectInfoKeys.map(k => ({
                        startTime: values?.projectInfoStartTime?.[k]?.[0]?.format('YYYY-MM-DD'),
                        endTime: values?.projectInfoStartTime?.[k]?.[1]?.format('YYYY-MM-DD'),
                        projectName: values?.projectInfoProjectName[k],
                        projectDesc: values?.projectInfoProjectDesc[k],
                        projectWorkDesc: values?.projectInfoProjectWorkDesc[k]
                    }));

                    const education = values?.educationKeys.map(k => ({
                        startTime: values?.educationStartTime?.[k]?.[0]?.format('YYYY-MM-DD'),
                        endTime: values?.educationStartTime?.[k]?.[1]?.format('YYYY-MM-DD'),
                        degree: values?.educationDegree[k],
                        graduateSchool: values?.educationGraduateSchool[k],
                        major: values?.educationMajor[k],
                        graduateSchoolType: values?.educationGraduateSchoolType[k],
                        graduateSchoolRank: values?.educationGraduateSchoolRank[k],
                        graduateSchoolDept: values?.educationGraduateSchoolDept[k],
                        academicYear: values?.educationAcademicYear[k]
                    }));

                    const training = values?.trainingKeys.map(k => ({
                        startTime: values?.trainingStartTime?.[k]?.[0]?.format('YYYY-MM-DD'),
                        endTime: values?.trainingStartTime?.[k]?.[1]?.format('YYYY-MM-DD'),
                        trainOrganize: values?.trainingTrainOrganize?.[k],
                        trainContent: values?.trainingTrainContent?.[k]
                    }));

                    const certificate = values?.certificateKeys.map(k => ({
                        certificateName: values?.certificateCertificateName?.[k],
                        certificateTime: values?.certificateCertificateTime?.[k]?.format('YYYY-MM-DD')
                    }));

                    const skill = values?.skillKeys.map(k => ({
                        proficiency: values?.skillProficiency[k],
                        skillDuration: values?.skillSkillDuration[k],
                        skillName: values?.skillSkillName[k]
                    }));

                    const skillLanguage = values?.skillLanguageKeys.map(k => ({
                        langType: values?.skillLanguageLangType?.[k],
                        listenSpeakAbility: values?.skillLanguageListenSpeakAbility?.[k],
                        readWriteAbility: values?.skillLanguageReadWriteAbility?.[k]
                    }));

                    const talentStandardSaveDTO = {
                        overseaExperienceFlag: values?.overseaExperienceFlag,
                        overseaEducationFlag: values?.overseaEducationFlag,
                        dutyCode: values?.dutyCode,
                        dutyName: values?.dutyName,
                        departmentName: values?.departmentName,
                        departmentCode: values?.departmentCode,
                        resumeChannelCode: values?.resumeChannelCode,
                        resumeChannelName: values?.resumeChannelName,
                        resourceRelation: values?.resumeAttachmentList?.uploadResourceFile
                            ? [values?.resumeAttachmentList?.uploadResourceFile]
                            : [],
                        talentName: values?.talentName,
                        phoneAreaCode: values?.phoneAreaCode,
                        talentPhone: values?.talentPhone,
                        talentEmail: values?.talentEmail,
                        address: Array.isArray(values?.address) ? values?.address?.join(',') : values?.address,
                        avatarRelation: values?.avatarRelation?.uploadResourceFile
                            ? [values?.avatarRelation?.uploadResourceFile]
                            : [],
                        talentIdCard: values?.talentIdCard,
                        talentBirth: values?.talentBirth?.format('YYYY-MM-01'),
                        talentSex: values?.talentSex,
                        talentStartWorkTime: values?.talentStartWorkTime?.format('YYYY-MM-01'),
                        talentNativePlace: Array.isArray(values?.talentNativePlace)
                            ? values?.talentNativePlace?.join(',')
                            : values?.talentNativePlace,

                        talentWorkType: values?.talentWorkType || '1', // 工作经历
                        talentWorkSaveDTOList: values?.talentWorkType === '1' ? workInfo : [], // 工作经历
                        talentProjectSaveDTOList: projectInfo, // 项目经历
                        talentEduSaveDTOList: education, // 教育经历
                        talentTrainSaveDTOList: training, // 培训经历
                        talentCertificateSaveDTOList: certificate, // 获得证书
                        talentSkillSaveDTOList: skill, // 专业能力
                        talentLangSaveDTOList: skillLanguage // 语言能力
                    };

                    const finalParams = {
                        recruitCode: recruitCode ?? values?.recruitCode,
                        talentOriginalSaveDTO: {
                            talentOriginalFileUrl: previewUrl,
                            resourceRelation
                        },
                        talentStandardSaveDTO
                    };
                    const existsParams = {
                        talentName: values?.talentName,
                        talentPhone: values?.talentPhone,
                        talentEmail: values?.talentEmail
                    };
                    console.log(finalParams);
                    // 从人才库录入新简历，需要查重， id用于判断是否为编辑简历
                    if (!id && query.origin === 'talent') {
                        const resArr = await Promise.all([
                            checkResumeExists(existsParams),
                            checkDuplicate(existsParams)
                        ]);
                        const checkData = resArr[0];
                        const duplicateArr = resArr[1];
                        setDuplicateResumeArr(duplicateArr);
                        if (checkData.code === 10000 && !isEmpty(checkData.data)) {
                            // 发现重复简历
                            setSubmitting(false);
                            setRepeatModalVisible(true);
                            const uplodedImgArr = values?.avatarRelation?.allFileList; // 新上传头像缩略图base64 or 旧头像url
                            const tempImg = await base64toURL(
                                uplodedImgArr && uplodedImgArr.length
                                    ? uplodedImgArr[0].thumbUrl || uplodedImgArr[0].url
                                    : ''
                            ); // 用于保存上传后的缓存图片
                            setRepeatTalentInfo({
                                finalParams,
                                originInfo: checkData.data,
                                currentInfo: existsParams,
                                _uplodedImg: tempImg
                            });
                            return;
                        }
                        if (checkData.code !== 10000) {
                            message.error(checkData.msg);
                            setSubmitting(false);
                            return;
                        }
                        submitResume(finalParams, duplicateArr.length); // 上传简历
                    } else {
                        // 从招聘页面录入简历
                        const duplicateArr = await checkDuplicate({
                            ...existsParams,
                            resumeId: id ?? null,
                            recruitCode: recruitCode ?? null
                        });
                        setDuplicateResumeArr(duplicateArr);
                        if (duplicateArr.length) {
                            // 发现重复简历
                            setRepeatTalentInfo({
                                // set用于保存的数据，Modal需要
                                finalParams,
                                currentInfo: existsParams
                            });
                            setSubmitting(false);
                            setRepeatModalVisible(true);
                        } else {
                            // 未发现重复简历
                            submitResume(finalParams, duplicateArr.length); // 上传简历
                        }
                    }
                }
            } catch (error) {
                console.error(error);
                message.error('提交失败');
                setSubmitting(false);
            }
        });
    };
    return (
        <Spin spinning={analysisLoading || detailLoading}>
            <PageContainer title="录入简历">
                <BottomAction>
                    <Button
                        onClick={() => {
                            eventTrack({
                                eventName:
                                    'personnel_management_recruitment_demand_list_detail_resume_enter_cancel_click',
                                pageName: 'personnel_management_recruitment',
                                eventProps: {
                                    click_context: query?.dutyName
                                }
                            });
                            goBack();
                        }}
                    >
                        取消
                    </Button>
                    <Button
                        type="primary"
                        onClick={() => {
                            eventTrack({
                                eventName:
                                    'personnel_management_recruitment_demand_list_detail_resume_enter_submit_click',
                                pageName: 'personnel_management_recruitment',
                                eventProps: {
                                    click_context: query?.dutyName
                                }
                            });
                            handleSubmit();
                        }}
                        loading={submitting}
                    >
                        提交
                    </Button>
                </BottomAction>
                <ResumeBrief
                    form={form}
                    eventTrackHandler={fieldName => {
                        // 这些埋点需求...公司没几个正常人了
                        eventTrack({
                            eventName: 'personnel_management_recruitment_demand_list_detail_resume_enter_input_click',
                            pageName: 'personnel_management_recruitment',
                            eventProps: {
                                click_context: `${query?.dutyName}-录入简历-${fieldName}`
                            }
                        });
                    }}
                />
                <Tabs
                    defaultActiveKey="1"
                    tabBarExtraContent={
                        <ResumeUpload
                            previewUrl={previewUrl}
                            onPreviewChange={url => {
                                setPreviewUrl(url);
                                setPreviewChanged(true);
                                setKeysIsReady(false);
                            }}
                            onChange={value => {
                                setResourceRelation([value]);
                            }}
                        >
                            <span style={{ color: '#FFA22D', cursor: 'pointer' }}>
                                <Icon type="upload" style={{ paddingRight: '6px' }} />
                                重新上传简历
                            </span>
                        </ResumeUpload>
                    }
                    onTabClick={key => {
                        const eventMap = {
                            1: 'personnel_management_recruitment_demand_list_detail_resume_enter_original_click',
                            2: 'personnel_management_recruitment_demand_list_detail_resume_enter_standard_click'
                        };
                        eventTrack({
                            eventName: eventMap[key],
                            pageName: 'personnel_management_recruitment',
                            eventProps: {
                                click_context: `${query?.dutyName}`
                            }
                        });
                    }}
                >
                    <TabPane tab="原始简历" key="1">
                        <div
                            onClick={() => {
                                eventTrack({
                                    eventName:
                                        'personnel_management_recruitment_demand_list_detail_resume_enter_original_upload_click',
                                    pageName: 'personnel_management_recruitment',
                                    eventProps: {
                                        click_context: `${query?.dutyName}`
                                    }
                                });
                            }}
                        >
                            <ResumePreview
                                previewUrl={previewUrl}
                                onPreviewChange={url => {
                                    setPreviewUrl(url);
                                    setPreviewChanged(true);
                                    setKeysIsReady(false);
                                }}
                                onChange={value => {
                                    setResourceRelation([value]);
                                }}
                            />
                        </div>
                    </TabPane>
                    <TabPane tab="标准简历" key="2" forceRender>
                        <Row>
                            <Col span={20}>
                                <ResumeBase form={form} />
                                <ResumeWorkInfo form={form} />
                                <ResumeProjectInfo form={form} />
                                <ResumeEducation form={form} />
                                <ResumeTraining form={form} />
                                <ResumeCertificate form={form} />
                                <ResumeSkill form={form} />
                                <ResumeSkillLanguage form={form} />
                                <ResumeOther form={form} />
                            </Col>
                            <Col span={4}>
                                <Anchor
                                    getContainer={() => getTabContainer()}
                                    offsetTop={10}
                                    style={{ marginLeft: 16 }}
                                >
                                    <Link href="#resume-base" title="个人信息" />
                                    <Link href="#resume-workInfo" title="工作经历" />
                                    <Link href="#resume-projectInfo" title="项目经验" />
                                    <Link href="#resume-education" title="教育经历" />
                                    <Link href="#resume-training" title="培训经历" />
                                    <Link href="#resume-certificate" title="获得证书" />
                                    <Link href="#resume-skill" title="专业技能" />
                                    <Link href="#resume-skillLanguage" title="语言能力" />
                                    <Link href="#resume-annex" title="附件" />
                                    {id && <Link href="#resume-other" title="入库情况" />}
                                </Anchor>
                            </Col>
                        </Row>
                    </TabPane>
                </Tabs>
                <ResumeRepeatModal
                    duplicateResumeArr={duplicateResumeArr}
                    isTalent={query.origin === 'talent'}
                    visible={repeatModalVisible}
                    talentInfo={repeatTalentInfo}
                    onCancel={() => {
                        setRepeatModalVisible(false);
                    }}
                    onOk={(isQuery, params) => {
                        setRepeatModalVisible(false);
                        if (isQuery) {
                            submitResume(params);
                        }
                    }}
                />
            </PageContainer>
        </Spin>
    );
};

export default Form.create({})(Record);
